/**
 * 
 */
package com.mattgarner.jaddas.node.data;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;

import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.SecondaryDatabase;
import com.sleepycat.je.SecondaryKeyCreator;


public class PrimaryKeyCreator implements SecondaryKeyCreator {

	public PrimaryKeyCreator() {
	}

	public boolean createSecondaryKey(SecondaryDatabase databaseSecondary,
			DatabaseEntry key, DatabaseEntry data, DatabaseEntry alternateKey)
			throws DatabaseException {

		byte[] rowBytes = data.getData();

		ByteArrayInputStream bais = new ByteArrayInputStream(rowBytes);
		DataInputStream buffer = new DataInputStream(bais);
		
		try {
			// reads the tuple header
			int tupleFlags = buffer.readByte(); // reserved for later use 
			int prikeyColumn = buffer.readUnsignedByte();
			//int prikeyType = buffer.readByte();
			
			int bytePos = 3;
			while(bytePos < rowBytes.length) {
			    int columnID = buffer.readUnsignedByte();
			    int fieldLength = buffer.readInt();

			    if(columnID == prikeyColumn) {
			    	byte[] fieldBytes = new byte[fieldLength];
			    	buffer.read(fieldBytes, 0, fieldLength);
			    	alternateKey.setData(fieldBytes);
			    	break;
			    } else {
			    	buffer.skip(fieldLength);
			    }
			    
			    bytePos += 5 + fieldLength;
			}

		} catch(IOException e) {
			return false;
		}
		
		return true;
	}

}
